'''
Created on Apr 14, 2011

@author: lrg
'''

class DMCodeGen(object):
    '''
    classdocs
    '''


    def __init__(self,modelClassName,pk,columns):
        '''
        Constructor
        '''
        self.modelClassName = modelClassName;
        self.dmClassName = modelClassName + "DM";
        self.pkList = pk
        self.columns = columns
        self.output = open(self.dmClassName+".java", 'w')
        self.varName = self.modelClassName[0:1].lower()+self.modelClassName[1:];
        
        singleEqualClause = " %s = ? "
        conditionClauseList = [singleEqualClause]*len(self.pkList)
        self.conditionClause = ("and".join(conditionClauseList)) % tuple(self.pkList)
        
        self.nonPKcolumns = [s for s in self.columns.keys() if s not in self.pkList]
        updateClauseList = [singleEqualClause]*len(self.nonPKcolumns)
        self.updateClause = (",".join(updateClauseList)) % tuple(self.nonPKcolumns)
        
    def generate(self):
        
        self.write (0,"public class %s extends DataManager implements %s { \n" % (self.dmClassName, self.dmClassName+("I")))
        self.write (1,"private static final String TABLE_NAME = TableNameConstants.____;   \\\\todo fill in the table name ")
        self.write (1,"private %s %s;" % (self.modelClassName, self.varName ))
        
        self.genSetterGetters()
        
        wrapOM = self.wrapOverrideMethod
        wrapOM(self.gen_getTableName)
        wrapOM(self.gen_getDeleteStatement)
        wrapOM(self.gen_getExistStatement)
        wrapOM(self.gen_insertStatement)
        wrapOM(self.gen_selectStatement)
        wrapOM(self.gen_updateStatement)
        wrapOM(self.gen_initializeDataObject)
        wrapOM(self.gen_initializeDeleteStatement)
        wrapOM(self.gen_initializeExistStatement)
        
        self.write (0,"}") 
        
    def gen_initializeExistStatement(self):
        
        self.write(1,"protected void initializeExistStatement(PreparedStatement statement) throws SQLException {")
        self.write(2,"int index = 1;")
        
        for field in self.pkList:
            if self.columns[field]=="int":
                setType = """setInt(%s)"""
            elif self.columns[field]=="String":
                setType = """setString("%s")"""
        
            self.write(2,"statement.%s;" % (setType % ("index++, get%s().get%s()" % (self.modelClassName,field.title()))))
        
        
    def gen_initializeDeleteStatement(self):
        
        self.write(1,"protected void initializeDeleteStatement(PreparedStatement statement) throws SQLException {")
        self.write(2,"int index = 1;")
        
        for field in self.pkList:
            if self.columns[field]=="int":
                setType = """setInt(%s)"""
            elif self.columns[field]=="String":
                setType = """setString("%s")"""
        
            self.write(2,"statement.%s;" % (setType % ("index++, get%s().get%s()" % (self.modelClassName,field.title()))))
                   
        
    def gen_initializeDataObject(self):
        
        self.write(1,"protected void initializeDataObject(ResultSet rs) throws SQLException {")
        
        for field in self.nonPKcolumns:
            if self.columns[field]=="int":
                getType = """rs.getInt("%s")"""
            elif self.columns[field]=="String":
                getType = """rs.getString("%s")"""
            elif self.columns[field]=="boolean":
                getType = """Converter.convert(rs.getString("%s"),false)"""
        
            self.write(2,"get%s().set%s(%s);" % (self.modelClassName,field.title(),(getType%(field))))
            
        
    def gen_updateStatement(self):
        
        self.write (1,"protected String getUpdteStatement(){")
        self.write (2, """return new String("update " + getFullTableName())
            .append(" set")
            .append( %s)
            .append(" where").append("%s").toString();
            """ % (self.updateClause, self.conditionClause))
        
    def gen_selectStatement(self):
        
        self.write (1,"protected String getSelectStatement(){")
        self.write (2, """return new StringBuffer("select * from " + getFullTableName())
            .append(" where").append("%s").toString();""" % (self.conditionClause))
        
    def gen_insertStatement(self):
        
        self.write (1,"protected String getInsertStatement(){")
        self.write (2, """return new StringBuilder("insert into " + getFullTableName())
            .append(" (%s)")
            .append(" values").append(" (%s)").toString();""" % (",".join(self.nonPKcolumns),",".join(["?"]*len(self.nonPKcolumns))))
        
    def gen_getExistStatement(self):
        
        self.write (1,"protected String getExistStatement(){")
        self.write (2,"""return new StringBufer("select 1 from " + getFullTablename())
            .append(" where").append("%s").toString();""" % (self.conditionClause))
        
    def gen_getDeleteStatement(self):
        
        self.write (1,"protected String getDeleteStatement(){")

        self.write (2, """return new StringBuilder("delete from " + getFullTableName())
        .append(" where").append("%s").toString();""" % (self.conditionClause))
        
    def gen_getTableName(self):

        self.write (1,"public String getTableName(){")
        self.write (2,"return TABLE_NAME;")
        
        
    def genSetterGetters(self):
        
        self.write (0,"")
        self.write (1,"public %s get%s(){" % (self.modelClassName, self.modelClassName))
        self.write (2,"return this.%s" % (self.varName ))
        self.write (1,"}")
        
        self.write (0,"")
        self.write (1,"public void set%s(%s %s){" % (self.modelClassName,self.modelClassName,self.varName))
        self.write (2,"this.%s = %s" % (self.varName,self.varName))
        self.write (1,"}")
        
    def wrapOverrideMethod(self,genMethod):
        self.write (0,"")
        self.write (1,"@Override")
        genMethod();
        self.write (1,"}")
        
    def write(self,k,s):    
        self.output.write("\t"*k + s + "\n");               
        